package com.next

class Task
{
    String name
    String description

    Double progress = 0

    User user

    static belongsTo = [activity: Activity]

    static constraints = {
        progress nullable: true, blank: true

        progress inList: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]*.toDouble()
        name maxSize: 64, unique: ['activity']
        description nullable: true, blank: true, type: "text"
        user nullable: true, blank: true
    }

    def springSecurityService

    def beforeInsert()
    {
        String username = springSecurityService?.getPrincipal()?.username
        user = User.findByUsername(username)
    }

    def afterUpdate()
    {
        def activityProgress = 0
        Integer count = activity.tasks.size()
        activity.tasks.each {
            activityProgress += it.progress
        }
        activityProgress = (activityProgress / count).toBigDecimal().setScale(1, BigDecimal.ROUND_DOWN).doubleValue()
        activity.progress = activityProgress
    }
}
